<?php

namespace App\Models;

use App\Models\ComModel;

class PiecesModel extends ComModel
{

    public $tablename;
    private $categorys;
    public $type;

    public function __construct(...$param)
    {
        parent::__construct();
        $this->table = 'pieces';
        $this->type = ['input', 'textarea', 'editor', 'file', 'files', 'media', 'keyvalue'];
    }

    private function _validate($data, $id = 0)
    {
        if (!$data['title']) {
            return ams_rt(1, '中文名称必须填写');
        } elseif (!$data['name']) {
            return ams_rt(1, '调用名称必须填写');
        } elseif (!$data['type'] || !in_array($data['type'], $this->type)) {
            return ams_rt(1, '请选择分类');
        }

        $data = esc($data);

        //重复检查
        if ($id) {
            $flag = $this->db->table($this->table)->where('id', $id)->countAllResults();
            if (!$flag) {
                return ams_rt(1, '数据不存在');
            }

            $flag = $this->db->table($this->table)->where('title', $data['title'])->where('id<>', (int) $id)->countAllResults();
            if ($flag) {
                return ams_rt(1, '中文名称已存在');
            }

            $flag = $this->db->table($this->table)->where('name', $data['name'])->where('id<>', (int) $id)->countAllResults();
            if ($flag) {
                return ams_rt(1, '调用名称已存在');
            }
        } else {
            $flag = $this->db->table($this->table)->where('title', $data['title'])->countAllResults();
            if ($flag) {
                return ams_rt(1, '中文名称已存在');
            }

            $flag = $this->db->table($this->table)->where('name', $data['name'])->countAllResults();
            if ($flag) {
                return ams_rt(1, '调用名称已存在');
            }
        }

        //格式化
        if ($data['type'] == 'files') {
            $data['content'] = json_encode($data['files']);
        } elseif ($data['type'] == 'media') {
            $data['content'] = json_encode($data['media']);
        } elseif ($data['type'] == 'keyvalue') {
            $data['content'] = json_encode($data['keyvalue']);
        } elseif ($data['type'] == 'input') {
            $data['content'] = $data['input'];
        } elseif ($data['type'] == 'textarea') {
            $data['content'] = $data['textarea'];
        } elseif ($data['type'] == 'file') {
            $data['content'] = $data['file'];
        } elseif ($data['type'] == 'editor') {
            $data['content'] = htmlspecialchars($data['editor']);
        }
        return ams_rt(0, 'ok', $data);
    }

    //添加
    public function add($data)
    {
        $rt = $this->_validate($data);
        if ($rt['code']) {
            return $rt;
        }
        $data = $rt['data'];

        $data = [
            'title' => $data['title'],
            'name' => $data['name'],
            'description' => isset($data['description']) ? $data['description'] : '',
            'type' => $data['type'],
            'content' => $data['content'],
            'displayorder' => 0,
            'updatetime' => time(),
        ];

        $this->db->table($this->table)->insert($data);
        $id = $this->db->insertID();
        if ($id) {
            if ($data['type'] == 'file' && $data['content']) {
                $this->attachments($data['content'], $this->table . '-' . $id);
            } elseif ($data['type'] == 'files' && $data['content']) {
                $con = json_decode($data['content']);
                foreach ($con as $fileid) {
                    $this->attachments($fileid, $this->table . '-' . $id);
                }
            }
            return ams_rt(0, '操作成功', $id);
        }
        $msg = $this->db->error();
        return ams_rt(1, '操作失败:' . ($msg['message'] ?? ''));
    }

    //添加
    public function edit($id, $data)
    {
        $id = intval($id);
        $rt = $this->_validate($data, $id);
        if ($rt['code']) {
            return $rt;
        }
        $data = $rt['data'];
        $data = [
            'title' => $data['title'],
            'name' => $data['name'],
            'description' => isset($data['description']) ? $data['description'] : '',
            'type' => $data['type'],
            'content' => $data['content'],
            'updatetime' => time(),
        ];
        $flag = $this->db->table($this->table)->where('id', $id)->update($data);
        if ($flag) {
            if ($data['type'] == 'file' && $data['content']) {
                $this->attachments($data['content'], $this->table . '-' . $id);
            }
            return ams_rt(0, '操作成功', $id);
        }
        $msg = $this->db->error();
        return ams_rt(1, '操作失败:' . ($msg['message'] ?? ''));
    }

    //删除
    public function del($id)
    {
        $id = intval($id);
        $flag = $this->db->table($this->table)->where('id', $id)->countAllResults();
        if (!$flag) {
            return ams_rt(1, '数据不存在');
        }
        $flag = $this->db->table($this->table)->where('id', $id)->delete();
        if ($flag) {
            return ams_rt(0, '操作成功', $id);
        }
        $msg = $this->db->error();
        return ams_rt(1, '操作失败:' . ($msg['message'] ?? ''));
    }

    public function get($id)
    {
        $id = intval($id);
        $row = $this->db->table($this->table)->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return [];
        }
        if ($row['content']) {
            if (in_array($row['type'], ['files', 'media', 'keyvalue'])) {
                $row[$row['type']] = json_decode($row['content'], true);
            }

            if ($row['type'] == 'file') {
                if ($row['content']) {
                    $row['file_info'] = $this->db->table('attachment')->select('filename,attachment')->where('id', intval($row['content']))->get()->getRowArray();
                }
            } elseif ($row['type'] == 'files') {
                if ($row['files']) {
                    foreach ($row['files'] as $k => $fileid) {
                        $row['files_info'][$k] = $this->db->table('attachment')->select('id,filename,attachment')->where('id', intval($fileid))->get()->getRowArray();
                    }
                }
            } elseif ($row['type'] == 'media') {
                if ($row['media']['video']) {
                    $row['media']['video_info'] = $this->db->table('attachment')->select('id,filename,attachment')->where('id', intval($row['media']['video']))->get()->getRowArray();
                }
                if ($row['media']['cover']) {
                    $row['media']['cover_info'] = $this->db->table('attachment')->select('id,filename,attachment')->where('id', intval($row['media']['cover']))->get()->getRowArray();
                }
            }
        }
        return $row;
    }

    public function getByName($name)
    {
        $name = ams_clean_xss($name);
        $row = $this->db->table($this->table)->where('name', $name)->get()->getRowArray();
        if (!$row) {
            return [];
        }

        if ($row['content']) {
            if (in_array($row['type'], ['files', 'media', 'keyvalue'])) {
                $row[$row['type']] = json_decode($row['content'], true);
            }
            if ($row['type'] == 'file') {
                if ($row['content']) {
                    $row['file_info'] = $this->db->table('attachment')->select('filename,attachment')->where('id', intval($row['content']))->get()->getRowArray();
                }
            } elseif ($row['type'] == 'files') {
                if ($row['files']) {
                    foreach ($row['files'] as $k => $fileid) {
                        $row['files_info'][$k] = $this->db->table('attachment')->select('id,filename,attachment')->where('id', intval($fileid))->get()->getRowArray();
                    }
                }
            } elseif ($row['type'] == 'media') {
                if ($row['media']['video']) {
                    $row['media']['video_info'] = $this->db->table('attachment')->select('id,filename,attachment')->where('id', intval($row['media']['video']))->get()->getRowArray();
                }
                if ($row['media']['cover']) {
                    $row['media']['cover_info'] = $this->db->table('attachment')->select('id,filename,attachment')->where('id', intval($row['media']['cover']))->get()->getRowArray();
                }
            }
        }
        return $row;
    }

    // 分页
    public function limit_page($page = 0, $size = 10, $total = 0, $param = [])
    {
        $page = max(1, (int) $page);
        $total = (int) $total;

        $param = esc($param);

        if ($size > 0 && !$total) {
            $select = $this->db->table($this->table)->select('count(*) as total');
            $param = $this->_limit_where($select, $param);
            $query = $select->get();
            if (!$query) {
                log_message('error', '数据查询失败：' . $this->table);
                return [[], $total, $param];
            }
            $data = $query->getRowArray();
            $total = (int) $data['total'];
            $param['total'] = $total;
            unset($select);
            if (!$total) {
                return [[], $total, $param];
            }
        }

        $select = $this->db->table($this->table);
        $order = 'displayorder asc,id desc';
        $param = $this->_limit_where($select, $param);
        $size > 0 && $select->limit($size, $size * ($page - 1));
        $query = $select->orderBy($order)->get();
        if (!$query) {
            log_message('error', '数据查询失败：' . $this->table);
            return [[], $total, $param];
        }
        $data = $query->getResultArray();
        $param['order'] = $order;
        $param['total'] = $total;

        return [$data, $total, $param];

    }

    /**
     * 条件查询
     *
     * @param    object    $select    查询对象
     * @param    intval    $where    是否搜索
     * @return    intval
     */
    protected function _limit_where(&$select, $param)
    {

        // 条件搜索
        if ($param) {

            // 关键字 + 自定义字段搜索
            if (isset($param['name']) && $param['name']) {
                $select->where('name', $param['name']);
            }

            if (isset($param['type']) && $param['type']) {
                $select->where('type', $param['type']);
            }

            if (isset($param['title'])) {
                $select->like('title', urldecode($param['title']));
            }
            // 时间搜索
            if (isset($param['sdate']) && $param['sdate']) {
                $select->where('addtime BETWEEN ' . max((int) strtotime($param['sdate'] . ' 00:00:00'), 1) . ' AND ' . ($param['edate'] ? (int) strtotime($param['edate'] . ' 23:59:59') : SITE_TIME));
            } elseif (isset($param['edate']) && $param['edate']) {
                $select->where('addtime BETWEEN 1 AND ' . (int) strtotime($param['edate'] . ' 23:59:59'));
            }

        }
        return $param;
    }

}
